package com.qingdai.business.aspect;


import com.qingdai.business.annotation.CheckAuthority;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Component
@Aspect
public class JwtAspect {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JwtUtil jwtUtil;

    @Pointcut("@annotation(com.qingdai.business.annotation.CheckAuthority)")
    public void CheckAuthorityPointCut() {
    }

    @Around("CheckAuthorityPointCut() && @annotation(checkAuthority)")
    public Object CheckAuthority(ProceedingJoinPoint joinPoint, CheckAuthority checkAuthority) throws Throwable {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        CommonResult authorities = jwtUtil.getAuthoritiesByRequest(request);
        if (authorities.getCode() != 200) {
            return authorities;
        }
        CommonResult userId = jwtUtil.getUserIdByRequest(request);
        String RedisToken = (String) redisTemplate.opsForValue().get("loginToken-UserId:" + userId);
        if (RedisToken == null) {
            return new CommonResult<>(400, "请重新登录");
        }
        String[] haveAuthorities = (String[]) authorities.getData();
        String[] setAuthorities = checkAuthority.authorities().split(",");
        for (String haveAuthority : haveAuthorities) {
            for (String setAuthority : setAuthorities) {
                if (Objects.equals(haveAuthority, setAuthority)) {
                    return joinPoint.proceed();
                }
            }
        }
        return new CommonResult<>(400, "不具备权限");
    }
}
